<?php
/*
 * 财务
 */
namespace Admin\Controller;
use Admin\Model\withdrawModel;
use Admin\Model\moneylogModel;
use Admin\Model\memberModel;
use Mobile\Model\tmpmsgModel;
use Mobile\Model\gradeModel;//用户等级
use Admin\Model\orderModel;
use Mobile\Controller\OrdercallbackController;


class FinanceController extends BaseController {
    
    public $withdrawModel;
    public $moneylogModel;
    public $memberModel;
    public $gradeModel;
    public $orderModel;
    public $king;
    public $grade_arr;
    
    
    public $status_text = array(
        //0提交待审核,1财务已打款,2审核拒绝
        0 => "待审核",
        1 => "已打款",
        2 => "已拒绝"
    );
    
    public function __construct() {
        parent::__construct();
        
        $this->withdrawModel = new withdrawModel();
        $this->moneylogModel = new moneylogModel();
        $this->memberModel = new memberModel();
        $this->gradeModel = new gradeModel();
        $this->orderModel = new orderModel();
        $this->grade_arr = $this->gradeModel->getField('grade_id,grade_name');
        
    }
    
    
    /*
     * 提现记录
     */
    protected function _get_where(){
        $data = param_filter($_GET, array("mobile","realname","status","uid"));
        $where = "1";
        if(is_set($data, 'mobile')){
            $where .= " AND mobile='".$data['mobile']."'";
        }
        if(is_set($data, 'realname')){
            $where .= " AND realname like '%".$data['realname']."%'";
        }
        if(is_set($data, 'status')){
            $where .= " AND status='".$data['status']."'";
        }
        if(is_set($data, 'uid')){
            $where .= " AND uid='".$data['uid']."'";
        }
        return $where;
        
    }
    
    
    /*
     * 佣金流水
     */
    protected function _get_money_where(){
        $where = " 1 ";
        
        $data = param_filter($_GET, array("order_id","user_id","logtype","fangan_type","page"));

        if(is_set($data, 'order_id')){
            $where .= " AND order_id='".$data['order_id']."'";
        }
        if(is_set($data, 'user_id')){
            $where .= " AND uid='".$data['user_id']."'";
        }
        if(is_set($data, 'logtype')){
            $where .= " AND logtype='".$data['logtype']."'";
        }
        if(is_set($data, 'fangan_type')){
            $where .= " AND fangan_type='".$data['fangan_type']."'";
        }
        
        return $where;
    }
    
    
    
    
    /*
     * 提现记录
     */
    public function index(){
        
        if($this->admininfo['role_id'] == 56){
            $this->redirect("/admin/finance/ningjiaobd");exit;
        }
        
        $page = get("p",1);
        $where = $this->_get_where();
        
        $datalist = $this->withdrawModel->getWithdrawList($where,$page);
        $count = $this->withdrawModel->getWithdrawCount($where);
        $this->assign('count',$count);
        
        $page = new \Think\Page($count, 100);
        $show = $page->show3();
        $this->assign('page', $show);
        
        $this->assign("datalist",$datalist);
        $this->assign("status_text",$this->status_text);
        
        $this->display();
    }
    
    
    /*
     * 提现记录导出
     */
    public function indexexcel(){
        $where = $this->_get_where();
        $datalist = $this->withdrawModel->getWithdrawLists($where);
        $datastr = "";
        foreach($datalist as $k=>$v){
            $datastr .= $v['uid'].",";//UID
            $datastr .= str_replace(array(",","'","\""),array("，","＂","＂"),$v['realname']).",";//转义
            $datastr .= $v['mobile'].",";//UID
            $datastr .= $v['bankname'].",";//UID
            $datastr .= $v['bankcard'].",";//UID
            $datastr .= $v['atm_money'].",";//UID
            $datastr .= $v['create_time'].",";//UID
            $status = $v['status'] ? (($v['status']==1) ? "已打款":"已拒绝") : "待审核";
            $datastr .= $status."\n";//UID
        }
        $header = "用户编号,真实姓名,手机号,银行名称,银行卡号,提现金额,申请时间,状态\n";
        $this->excel($datastr,$header,$excel_name='提现记录-');
    }   
    
    
    /*
     * 每月导出上个月奖励
     */
    public function monthexcel(){
        $where = array(
//            'create_time' => array(
//                'between' => array(
//                    date('Y-m-1 00:00:00', strtotime('-1 month')),
//                    date('Y-m-1 00:00:00'),
//                )
//            ),
            'mtype' => array('in',array(1,12)),
            'is_charge' => 0,
            'logtype' => 1
        );
        $uids = $this->moneylogModel->where($where)->group('uid')->getField('uid',true);
        $datalist = array();
        foreach ($uids as $uid) {
            $member = $this->memberModel->where(array('uid'=>$uid))->find();
            
            $where['uid'] = $uid;
            $where['mtype'] = 1;
            $money = $this->moneylogModel->where($where)->sum('money');
            
            $where['mtype'] = 12;
            $prize = $this->moneylogModel->where($where)->sum('money');
            
            $datalist[] = array(
                'realname' => $member['realname'],
                'mobile' => $member['mobile'],
                'uid' => $member['uid'],
                'money'=> $money,
                'prize' => $prize
            );
        }
        
        $datastr = "";
        foreach($datalist as $k=>$v){
            $datastr .= $v['uid'].",";//UID
            $datastr .= str_replace(array(",","'","\""),array("，","＂","＂"),$v['realname']).",";//转义
            $datastr .= $v['mobile'].",";//UID
            $datastr .= $v['money'].",";//UID
            $datastr .= $v['prize']."\n";//UID
        }
        $header = "用户编号,真实姓名,手机号,金额,奖励金额\n";
        $this->excel($datastr,$header,$excel_name='奖金统计-');
    }   
    
    
    public function excel($datastr,$header='',$excel_name=''){

        $filename = $excel_name.date('Y-m-d').'.csv'; //设置文件名
        header("Content-type:text/csv;charset=utf-8");
        header("Content-Disposition:attachment;filename=".$filename);
        header('Cache-Control:must-revalidate,post-check=0,pre-check=0');
        header('Expires:0');
        header('Pragma:public');
        echo  $content = "\xEF\xBB\xBF".$header.$datastr; //添加BOM
	    
	}
    
    /*
     * 佣金流水
     * 秒结类/分销 重消佣金
     * 1分销佣金,2重消币 3现金电子币 4重消佣金7领导奖6车房奖5互助奖8分红奖
     */
    public function liushui(){
        
        $page = get("p",1);
        $where = $this->_get_money_where();
        if(!$_GET['type']){
            $_GET["type"] = 0;
        }
        switch($type = $_GET["type"]){
            case 0:$where .= " AND (mtype=1 or mtype=12) ";break;
            case 1:$where .= " AND (mtype=1)";break;
            case 2:$where .= " AND (mtype=2)";break;
            case 3:$where .= " AND (mtype=3)";break;
            case 4:$where .= " AND (mtype=4)";break;
        }
        $datalist = $this->moneylogModel->getMoneylogList($where,$page);
        $count = $this->moneylogModel->getMoneylogCount($where);
        $this->assign('count',$count);
        
        $page = new \Think\Page($count, 100);
        $show = $page->show3();
        $this->assign('page', $show);
        
        $params = "?order_id=".get('order_id')."&user_id=".get('user_id')."&uid".get('uid')."&logtype=".get('logtype')."&fangan_type=".get('fangan_type')."&p=".get('p');
        $this->assign('params',$params);
        
        $this->assign("datalist",$datalist);
        $this->assign('type',$type);
        $this->display();
    }
    
    public function excash(){
    
        $page = get("p",1);
        $where = $this->_get_money_where();
        $where .= " AND mtype=4";
    
        $datalist = $this->moneylogModel->getMoneylogList($where,$page);
        $count = $this->moneylogModel->getMoneylogCount($where);
        $this->assign('count',$count);
    
        $page = new \Think\Page($count, 100);
        $show = $page->show3();
        $this->assign('page', $show);
        $this->assign("datalist",$datalist);
        $this->display('cash');
    }
    

    
    
    

    /*
     * 佣金流水
     * 现金流水
     * 1分销佣金,2重消币 3现金电子币 4重消佣金7领导奖6车房奖5互助奖8分红奖
     */
    public function cash(){
    
        $page = get("p",1);
        $where = $this->_get_money_where();
        $where .= " AND mtype=3 ";
    
        $datalist = $this->moneylogModel->getMoneylogList($where,$page);
        $count = $this->moneylogModel->getMoneylogCount($where);
        $this->assign('count',$count);
    
        $page = new \Think\Page($count, 100);
        $show = $page->show3();
        $this->assign('page', $show);
    
        $this->assign("datalist",$datalist);

        $this->display();
    }
     public function score(){
    
        $page = get("p",1);
        $where = $this->_get_money_where();
        $where .= " AND mtype=2 ";
    
        $datalist = $this->moneylogModel->getMoneylogList($where,$page);
        $count = $this->moneylogModel->getMoneylogCount($where);
        $this->assign('count',$count);
    
        $page = new \Think\Page($count, 100);
        $show = $page->show3();
        $this->assign('page', $show);
    
        $this->assign("datalist",$datalist);

        $this->display();
    }
    
    public function stock(){
        $page = get("p",1);
        $where = $this->_get_money_where();
        $where .= " AND mtype=4 ";
    
        $datalist = $this->moneylogModel->getMoneylogList($where,$page);
        $count = $this->moneylogModel->getMoneylogCount($where);
        $this->assign('count',$count);
    
        $page = new \Think\Page($count, 100);
        $show = $page->show3();
        $this->assign('page', $show);
        $this->assign("datalist",$datalist);
        $this->display();
    }

    
    
  
    
    /*
     * 分页
     */
    public function liushuiexcelpage(){
        $mtype = get('mtype',1);
        $where = $this->_get_money_where();
        $where .= " AND mtype=".$mtype;
        
        $count = $this->moneylogModel->getMoneylogCount($where);
        $allpage= ceil($count/5000);
        
        return_json(0,'请稍后',$allpage);
        
    }
    
    
    /*
     * 导出
     */
    public function liushuiexcel(){
    
        $mtype = get('mtype',1);
        $where = $this->_get_money_where();
        
        if($mtype==1) {
            $where .= " and (mtype=12 or mtype=1)";
        }else{
            $where .= " AND mtype=".$mtype;
        }
        
        $p = get('p',1);
        $datalist = $this->moneylogModel->getMoneylogList2($where,$p);

        $datastr = "";
        
        foreach($datalist as $k=>$v){
            
            $datastr .= $v['log_id'].",";//UID
            $datastr .= $v['uid'].",";//UID
            $datastr .= str_replace(array(",","'","\""),array("，","＂","＂"),$v['nickname']).",";//转义
            
            $datastr .= str_replace(array(",","'","\""),array("，","＂","＂"),$v['content']).",";//转义
            
            
            
            $logtype = $v['logtype'] ? "收入" : "支出";
            $datastr .= $logtype.",";//UID
            
            $datastr .= $v['money'].",";//UID
            $datastr .= $v['order_paymoney'].",";//UID
            $datastr .= $v['from_jibie'].",";//UID
            $datastr .= $v['order_id'].",";//UID
            $datastr .= $v['order_uid'].",";//UID
            $datastr .= str_replace(array(",","'","\""),array("，","＂","＂"),$v['order_nickname']).",";//转义
            
            $datastr .= $v['create_time'].",";//UID
            $datastr .= $v['fangan_type'].",";//UID
            $datastr .= $v['bili']."\n";//UID
   
        }
        
        if($mtype==1){
            $header = "编号,用户ID,昵称,描述,类型,佣金金额,订单金额,级别,订单号,下单人ID,下单人昵称,时间,方案,比率\n";
            $excel_name='佣金流水-'."第".$p."页-";
        }else if($mtype==2){
            $header = "编号,用户ID,昵称,描述,类型,微币金额,订单金额,级别,订单号,下单人ID,下单人昵称,时间,方案,比率\n";
            $excel_name='微币流水-'."第".$p."页-";
        }else if($mtype==3){
            $header = "编号,用户ID,昵称,描述,类型,金币金额,订单金额,级别,订单号,下单人ID,下单人昵称,时间,方案,比率\n";
            $excel_name='金币流水-'."第".$p."页-";
        }else if($mtype==9){
            $header = "编号,用户ID,昵称,描述,类型,金额,订单金额,级别,订单号,下单人ID,下单人昵称,时间,方案,比率\n";
            $excel_name='抗癌公社流水-'."第".$p."页-";
        }
        
        
        
        $this->excel($datastr,$header,$excel_name);
        
    }
    
    public function shenhe(){
        
        $atm_id = get('atm_id');
        
        $where = array(
            'atm_id' => $atm_id
        );
        
        $res = $this->withdrawModel->getWithdraw($where);
        
        if(empty($res)){
            return_json(1,"当前申请不存在");
        }
        
        if($res['status'] == 0 || ($res['status'] == 2)){
            //可以同意
            $data = array(
                "shenhe_time" => date("Y-m-d H:i:s"),
                "status" => 1,//0提交待审核,1财务已打款,2审核拒绝
                "admin_username" => $this->admininfo['username'],
            );
            $rr = $this->withdrawModel->editWithdraw($where, $data);
            if($rr){
                //发送模板消息
                $this->_tixianMsg($res,$res['uid']);
                return_json(0,"已审核通过,请财务及时打款!");
            }
            
        }
        
        return_json(1,"当前状态不能审核");
        
    }
    
    /*
     * 微信钱包提现打款
     */
    public function dakuan(){
    
        $atm_id = get('atm_id');
    
        $where = array(
            'atm_id' => $atm_id
        );
    
        $res = $this->withdrawModel->getWithdraw($where);
    
        if(empty($res)){
            return_json(1,"当前申请不存在");
        }
    
        if($res['status'] == 0 || ($res['status'] == 2)){
            
            //调用企业付款直接进行打款操作
            if($res['openid']){
                $order_data = array(
                    'trade_no' => $atm_id,
                    'openid' => $res['openid'],
                    'realname' => $res['realname'],
                    'amount' => $res['withdraw_money']*100, 
                    'desc' => '编号：'.$res['uid'].' 姓名：'.$res['realname'],
                    'ip' => $_SERVER["REMOTE_ADDR"],
                    'check_name' => 'FORCE_CHECK'
                );
                
            }else{
                return_json(1,"该提现记录无openid，无法提现");
            }
            
            
            $pay = new \Mobile\Controller\PaywechatController();
            $pay_check = $pay->qiyePay($order_data);
            
            //提现成功
            if($pay_check){
                
                //提现成功后，对配置文件账户进行扣减
                M('config')->where('id=158')->setDec('cvalue',$res['withdraw_money']);
                
                $data = array(
                    "shenhe_time" => date("Y-m-d H:i:s"),
                    "status" => 1,//0提交待审核,1财务已打款,2审核拒绝
                    "admin_username" => $this->admininfo['username'],
                );
                $rr = $this->withdrawModel->editWithdraw($where, $data);
                if($rr){       
                    //发送模板消息
                    $this->_tixianMsg($res,$res['uid']);
                    return_json(0,"已打款成功，提现会在几分钟内到帐!");
                }
                
                
                
               
                
            }else{
                return_json(1,"提现失败，请稍后重试");
            }
           
            
           
    
        }
    
        return_json(1,"当前状态不能审核");
    
    }

    /*
     * 提现提醒
     */
    protected function _tixianMsg($tixian,$uid){
        //判断是否关注, 没关注就别发了
        $where = array("uid"=>$uid);
        $userinfo = $this->memberModel->getMember($where);
        
        if(!$userinfo['openid']){
            //TODO
              return false;
        }
        //发送模板消息
        $msg = $this->_tixianTmp($tixian,$userinfo);//拼接模板消息
    
        $msgttt = array(
            "uid" => $userinfo['uid'],
            "openid" => $userinfo['openid'],
            "nickname" => $userinfo['nickname'],
            "groupid" => -1,
            "content" => $msg,
            "send_priority" => 1,
            "create_time" => time(),
            "send_time" => time(),
            "status" => -1,
            "send_plan_time" => time()
        );
        $tmpmsgModel = new tmpmsgModel();
        $tmpmsgModel->addtmpmsg($msgttt);//添加消息到数据库队列
    
        return true;
    }
    
    
    
    
    
    /*
     * 升级消息
     *
{{first.DATA}}

提现金额:{{money.DATA}}
提现时间:{{timet.DATA}}
{{remark.DATA}}

     * 拼接模板消息
     */
    protected function _tixianTmp($tixian,$userinfo){
    
        $tmp_id = $this->tmpl['TIXIAN_OK']['tmp_id'];
		$color = $this->tmpl['TIXIAN_OK']['color'];
    
        $url = get_domain()."/mobile/withdraw/lists/";
        $footer ='\\n'."点击查看详情...";
        $msg = array(
            "touser" => $userinfo['openid'],
            "template_id" => $tmp_id,//'i30GUItoDC_ImcLz_7je9EDdQ0XUp65cnPO5BBxpHhE',
            'url' => $url,
            "topcolor" => $color,
            'data' => array(
                'first' => array(
                    'value' => urlencode("恭喜,你的提现申请已通过,资金会在三个工作日内到账,如有疑问请联系客服~"),
                    'color' => $color
                ),
                'money' => array(
                    'value' => urlencode($tixian['atm_money']),//原先等级
                    'color' => $color
                ),
                'timet' => array(
                    'value' => urlencode($tixian['create_time']),//new等级
                    'color' => $color
                ),
                'remark' => array(
                    'value' => urlencode($footer),
                    'color' => $color
                ),
            ),
        );
    
        return $msg = urldecode(json_encode($msg));
    }
    
     /*
     * 佣金积分
     */
    public function chargeprizemoney(){
        if(IS_AJAX){
            $this->_chargeMoney('prize_money', '奖励佣金', 12);
        }
        $this->display();
    }
    
     /*
     * 佣金
     */
    public function chargemoney(){
        if(IS_AJAX){
            $this->_chargeMoney('money', '佣金', 1);
        }
        $this->display();
    }
    
    public function chargescore(){
        if(IS_AJAX){
            if($_POST['charge_money']%1300!=0) {
                return_json(1,"必须充值1300的倍数");
            }
            $this->_chargeMoney('score', '积分', 2);
        }
        
        $this->display();
    }
    
    public function chargestock(){
        if(IS_AJAX){
            $this->_chargeMoney('stock', '库存', 4);
        }
        
        $this->display();
    }
    
    /*
     * 充值
     */
    public function charge(){
        if(IS_AJAX){
            $this->_chargeMoney('cash_money', '现金', 3);
        }
        $this->display();
    }
    
 /*
     * 充值积分
     */
    protected function _chargeMoney($type,$content,$mtype){
            $data = param_filter($_POST, array('uid','charge_money','note'),array('uid','charge_money','note'),$filter=true,true);
    
            if(empty($data)){
                return_json(1,"请填写必填的信息");
            }
            $data[$type] = $data['charge_money'];
    
            //写cookie 防止重复提交同一个操作
            cookie($data["uid"].$type,$data[$type],60);
    
            if($data[$type]>'5000000'){
                return_json(1,"单次充值金额不能大于500万");
            }
    
            $where = array(
                "uid" => $data["uid"]
            );
            $user = $this->memberModel->getMember($where);
            if(!$user){
                return_json(1,"该用户不存在");
            }
            //$user["mobile_check"]==1 &&
            if($user["status"]==1){
                if($data['charge_money']!=0) {
                    $result = $this->memberModel->where($where)->setInc($type,$data['charge_money']);
                    $userinfo = $this->memberModel->getMember($where);
                    if($result){
                        $this->_addChargeLog($user['uid'], $mtype, $data['charge_money'], $data);
                        if($mtype==4 && $data['charge_money']>0) {
//                            $ordercallback = new OrdercallbackController(array('baodan'=>true));
//                            $ordercallback->handelChargeStock($userinfo, $data['charge_money'], 4);
                        }
                        if($mtype==4 && $data['charge_money']<0){
//                            $this->memberModel->where(array('uid'=>$user['uid']))->setInc('canbaodan_number',$data['charge_money']);
                        }
                    
                        $data['mtype'] = $mtype;
                        $data['money'] = $data['charge_money'];
                        $this->_chargeMsg($userinfo,$data);//发送充值通知
                        return_json(0,"充值成功,资金已存入用户账户","","/admin/finance/chargelog");
                    }
                }
                
                return_json(0,"充值成功");
            }
            return_json(1,"用户状态异常");
    }
    
    protected function _addChargeLog ($uid,$mtype,$money,$param) {
        $user = $this->memberModel->where(array('uid'=>$uid))->find();
        if($mtype==1) {
            $left = $user['money']+$user['lock_money'];
        }
        if($mtype==2) {
            $left = $user['score'];
        }
        if($mtype==3) {
            $left = $user['cash_money'];
        }
        if($mtype==4) {
            $left = $user['stock'];
        }
        
        $data = array(
            "uid" => $user["uid"],
            "nickname" => $user["nickname"],
            "mtype" => $mtype,
            "content" => "后台调整",
            "money" => abs($money),
            "logtype" => $money>0?1:0,
            "create_time" => date('Y-m-d H:i:s'),
            "manager_username" => $this->admininfo["username"],
            "cash_money" => $left,//余额
            "note" => $param["note"],
            "is_charge" => 1,
            'un_lock' => 1,
        );
        return $this->moneylogModel->add($data);
    }

        //账户查询
    public function account() {
        $page = get("p", 1);

        $m = M('member');
        $datalist = $m->limit(($page - 1) * 50, 50)->select();
        $count = $m->count();
        $this->assign('count', $count);

        $page = new \Think\Page($count, 50);
        $show = $page->show3();
        $this->assign('page', $show);

        $this->assign("datalist", $datalist);

        $this->display();
    }

    //报单升级
    public function upgrade() {
        if (IS_AJAX) {
            $data = param_filter($_POST, array('mobile', 'realname', 'refer_mobile', 'grade_id'), array('mobile'), $filter = true, true);

            if (empty($data)) {
                return_json(1, "请填写数据");
            }
            /*  if(cookie($data["mobile"]."upgrade") == $data["tihuo_money"] ){
              return_json(1,"请勿重复提交同样的操作","","/admin/finance/upgrade");
              }
              //写cookie 防止重复提交同一个操作
              cookie($data["mobile"]."upgrade",$data["tihuo_money"],60);
             */

            if (!$data['tihuo_money']) {
                $data['tihuo_money'] = 0;
            }

            $data['tihuo_money'] = 0; //固定为0


            if (!check_mobile($data['mobile'])) {
                return_json(1, "手机号不合法，请检查后修改");
            }



            $m = $this->memberModel;

            //判断是否是新用户，老用户禁止报单
            $new_map['mobile'] = $data['mobile'];
            $new_user = $m->where($new_map)->find();
            if ($new_user) {
                return_json(1, "该用户已存在，无法完成报单");
            }

            if (!$data['refer_mobile']) {
                return_json(1, "请填写推荐人手机号");
            }

            //根据手机号，查到推荐人
            $refer_mobile = $data['refer_mobile'];
            $refer_map['mobile'] = $refer_mobile;
            $refer = $m->where($refer_map)->find();
            if (!$refer) {
                return_json(1, "该推荐人不存在");
            }

            $res['refer_uid'] = $refer['uid'];
            $res['refer_nickname'] = $refer['realname'] ? $refer['realname'] : $refer['nickname'];
            $res['mobile'] = $data['mobile'];
            $res['realname'] = $data['realname'];
            $res['grade_id'] = 2;
            $res['create_time'] = date('Y-m-d H:i:s');
            if ($m->add($res)) {

                $map['mobile'] = $data['mobile'];
                //提交数据后的用户信息
                $userinfo = $m->where($map)->find();


                //推荐人变更日志
                $content = "（后台注册：）" . "无" . "->" . $userinfo['refer_nickname'];
                $this->_addActionlog($userinfo, 3, $content);

                //等级变更日志
                $content = "（后台注册：）" . "无" . "->CEO";
                $this->_addActionlog($userinfo, 1, $content);

                //报单日志
                $money = M("moneylog");
                $change_money = array(
                    "uid" => $userinfo["uid"],
                    "nickname" => $userinfo["realname"],
                    "mtype" => 11,
                    "content" => "CEO报单",
                    "money" => $data["tihuo_money"],
                    "logtype" => 1,
                    "create_time" => date('Y-m-d H:i:s'),
                    "manager_username" => $this->admininfo["username"],
                    "is_charge" => 1,
                    "un_lock" => 1
                );
                $money->add($change_money);


                //生成订单
                $order_id = $this->_addOrder($userinfo, $data['tihuo_money'], 0);

                //两级分销
                if ($data['tihuo_money'] > 0) {
                    $this->fenxiao($userinfo, $data['tihuo_money'], $order_id);
                }

                //处理上级逻辑
                $this->_shengji($userinfo['refer_uid']);




                return_json(0, "报单成功", "", "/admin/finance/upgradelog");
            } else {
                return_json(1, '充值失败');
            }
        }

        $this->display();
    }

    /*
     * 无限查询上级是否升级
     */

    protected function _shengji($refer_uid) {
        $where = array(
            'uid' => $refer_uid
        );
        $top = $this->memberModel->where($where)->find();
        if (!$top) {
            return;
        }
        //ceo
        if ($top['grade_id'] == 2) {
            $isking = $this->_isKing($top['uid']);
            if ($isking) {
                $data['grade_id'] = 3;
                $this->memberModel->where($where)->save($data);
                //升级模板消息
                $this->_shengjiMsg($top, $top['grade_id'], $data['grade_id']);
                //升级日志
                $content = $this->grade_arr[$top['grade_id']] . "->" . $this->grade_arr[$data['grade_id']];
                $this->_addActionlog($top, 1, $content);
            }
        }
        //king
        else if ($top['grade_id'] == 3) {
            $isbigking = $this->_isBigKing($top['uid']);
            if ($isbigking) {
                $data['grade_id'] = 4;
                $this->memberModel->where($where)->save($data);
                //升级模板消息
                $this->_shengjiMsg($top, $top['grade_id'], $data['grade_id']);
                //升级日志
                $content = $this->grade_arr[$top['grade_id']] . "->" . $this->grade_arr[$data['grade_id']];
                $this->_addActionlog($top, 1, $content);
            }
        }
        $this->_shengji($top['refer_uid']);
    }

    /*
     * 判断是否升级皇冠
     * return boole
     */

    protected function _isKing($uid){
        $where = array(
            'refer_uid' => $uid,
            'grade_id' => array('in',array(2,3,4))
        );
        $num = $this->memberModel->where($where)->count(); 
        if($num >= 6){
            return true;
        }else{
            return false;
        }
    }
    
    /*
     * 判断是否升级大皇冠
     * return boole
     */
    protected function _isBigKing($uid){
        $where = array(
            'refer_uid' => $uid,
            'grade_id' => array('in',array(3,4))
        );
        $onenum = $this->memberModel->where($where)->count();
        $onelist = $this->memberModel->where("refer_uid='".$uid."'")->field('uid')->select();
        $twonum = 0;
        foreach($onelist as $v){
            $where = array(
                'refer_uid' => $v['uid'],
                'grade_id' => array('in',array(3,4))
            );
            $num = $this->memberModel->where($where)->count();
            $twonum += $num; 
        }
        if(($onenum+$twonum)>=6){
            return true;
        }else{
            return false;
        }
        
    }
 
	/*
	 * actionlog   1等级变更   3手机号码变更 日志
	 */
	protected function _addActionlog($userinfo,$logtype,$content){
	     $change = array(
	        "log_type" => $logtype,
	        "action_username" => $this->admininfo["username"],
	        "target_uid" => $userinfo["uid"],
	        "target_username" => $userinfo["realname"],
	        "create_time" => date('Y-m-d H:i:s'),
	        "content" => $content
	    );
	     $m = M("actionlog");
	     $m->add($change);  
	}
	
	/*
	 * 后台报单，生成订单
	 */
	protected function _addOrder($userinfo,$money,$order_type){
	    
	    $now = date('Y-m-d H:i:s');
	    //查找订单所属的皇冠
	    $king = $this->getKing($userinfo['refer_uid']);
	    $order = array(
	        'uid' => $userinfo['uid'],
	        'order_sn' => 'WX'.date("YmdHis").sprintf("%05d", $this->uid).rand(10,99),
	        'realname' => $userinfo['realname'],
	        'nickname' => $userinfo['realname'],
	        'refer_uid' => $userinfo['refer_uid'],
	        'refer_nickname' => $userinfo['refer_nickname'],
	        'checked' => 2,
	        'pay_time' => $now,
	        'create_time' => $now,
	        'send_time' => $now,
	        'order_title' => "后台注册报单",
	        'delivery_mobile' => $userinfo['mobile'],
	        'order_type' => $order_type,
	        'order_cashmoney' => $money,
	        'pay_orgmoney' => $money,
	        'all_money' => $money,
	        'king_uid' => $king['uid'],
	        'king_realname' => $king['realname']
	    );
	    
	    $o = M('order');
	    $orderid = $o->add($order);
	    return $orderid;
	}
    
    /*
     * 充值log
     */
    public function chargelog(){

        $page = get("p",1);
        $where = $this->_get_money_where();
        $where .= " AND is_charge=1";
        
        $datalist = $this->moneylogModel->getMoneylogList($where,$page);
        $count = $this->moneylogModel->getMoneylogCount($where);
        $this->assign('count',$count);
        
        $page = new \Think\Page($count, 100);
        $show = $page->show3();
        $this->assign('page', $show);
        
        $this->assign("datalist",$datalist);
        
        $this->display();
        
    }
    
    /*
     * 报单升级log
     */
    public function upgradelog(){
        $page = get("p",1);
        $where = $this->_get_money_where();
        $where .= " AND mtype=11 AND is_charge=1";
        
        $datalist = $this->moneylogModel->getMoneylogList($where,$page);
        $count = $this->moneylogModel->getMoneylogCount($where);
        $this->assign('count',$count);
        
        $page = new \Think\Page($count, 100);
        $show = $page->show3();
        $this->assign('page', $show);
        
        $this->assign("datalist",$datalist);
        
        $this->display();
    }
    
    /*
     * leftmoney  公司账户用户总余额的统计
     */
    public function leftmoney(){
        
     
       $money = array(
           'money' => $this->memberModel->sumLeft('money'),
           'cash_money' => $this->memberModel->sumLeft('cash_money'),
           'lock_money' => $this->memberModel->sumLeft('lock_money'),
           'score' => $this->memberModel->sumLeft('score'),
           'stock' => $this->memberModel->sumLeft('stock'),
           'bzj_money' => $this->memberModel->sumLeft('bzj_money'),
           'pxf_money' => $this->memberModel->sumLeft('pxf_money'),
       );
       
       $tixian = $this->withdrawModel->sumTixian();
       
       $this->assign('money',$money);
       $this->assign('tixian',$tixian);

       $this->display();
       
    }
    

    

  

  
    /*
     * 充值成功模板消息
     * 拼接模板消息
     */
    protected function _sendchargetmp($userinfo,$data){
    
        $tmp_id = $this->tmpl['CZ_OK']['tmp_id'];
        $color = $this->tmpl['CZ_OK']['color'];
        $color = '#000';
        
        //$footer ='\\n'."点击查看详情...";
        $userinfo = $this->memberModel->where(array('uid'=>$userinfo['uid']))->find();
        if($data['mtype']==2){
            $txt = '积分';
        }elseif($data['mtype']==3){
            $txt = C('CASH_NAME');
            $yue = $userinfo['cash_money'];
            $url = get_domain()."/mobile/moneylists/cash";
        }elseif($data['mtype']==1){
            $txt = C('YONGJIN_NAME');
            $yue = $userinfo['money']+$userinfo['lock_money'];
            $url = get_domain()."/mobile/moneylists/money";
        }elseif($data['mtype']==4){
            $txt = '库存';
            $yue = $userinfo['stock'];
//            $url = get_domain()."/mobile/moneylists/ex_cash";
        }
    
        $title = "尊敬的用户，后台已成功充值".$txt;
//        if($data['song_money']>0){
//            $title .= '\\n赠送龙币:'.$data['song_money'];
//        }
        
        $msg = array(
            "touser" => $userinfo['openid'],
            "template_id" => $tmp_id,//
            'url' => $url,
            "topcolor" => $color,
            'data' => array(
                'first' => array(
                    'value' => urlencode($title),
                    'color' => $color
                ),
                'keyword1' => array(
                    'value' => urlencode(round($data['money'],2)),//金额
                    'color' => $color,
                ),
                'keyword2' => array(
                    'value' => urlencode(date("Y-m-d H:i:s")),//充值时间
                    'color' => $color,
                ),
                'keyword3' => array(
                    'value' => urlencode($yue),//余额
                    'color' => $color,
                ),
            ),
        );
    
        return $msg = urldecode(json_encode($msg));
    }
    
    
    
    /*
     * 通知,模板消息
     * 1
     */
    protected function _chargeMsg($userinfo,$order){
        //发送升级模板消息
        //判断是否关注, 没关注就别发了
        if(!$userinfo['subscribe']){
            //return false;
            //TODO
        }
    
        //发送模板消息
        $msg = $this->_sendchargetmp($userinfo,$order);//拼接模板消息
    
        $msgttt = array(
            "uid" => $userinfo['uid'],
            "openid" => $userinfo['openid'],
            "nickname" => $userinfo['nickname'],
            "groupid" => -1,
            "content" => $msg,
            "send_priority" => 1,
            "create_time" => time(),
            "send_time" => time(),
            "status" => -1,
            "send_plan_time" => time()
        );
        $tmpmsgModel = new tmpmsgModel();
        $tmpmsgModel->addtmpmsg($msgttt);//添加消息到数据库队列
    
        return true;
    }

    /*
     * 后台报单2级分销逻辑
     * $userinfo  下单人信息 
     * $money 报单金额
     */
    public function fenxiao($userinfo,$money,$order_id){
        $one_bili = C('CEO_ONE');
        $two_bili = C('CEO_TWO');
        $king_bili = C('KING_ZHITUI');
        $order = $this->orderModel->where("order_id = '".$order_id."'")->find();
        //第一级
        $refer_uid = $userinfo['refer_uid'];
        $one = $this->memberModel->where("uid = '".$refer_uid."'")->find();
        if($one){
            if($one['grade_id'] >= 3){
                //皇冠直推CEO分佣
                $king_money = $money*$king_bili;
                $this->memberModel->where("uid = '".$refer_uid."'")->setInc('money',$king_money);
                //log
                $king = $this->memberModel->where("uid = '".$refer_uid."'")->find();
                $this->fenxiao_log($userinfo,$king,$king_money,$money,'皇冠直推CEO分佣',1,$order_id);
                //模板消息
                $content = "皇冠直推CEO分佣：订单".$order['order_id'].$order['order_title'].",".$order['realname']."(".$order['uid'].")";
                $this->_shouruMsg($king, $order, $king_money, $content);
                return;
            }
            $one_money = $money*$one_bili;
            $this->memberModel->where("uid = '".$refer_uid."'")->setInc('money',$one_money);
            $one = $this->memberModel->where("uid = '".$refer_uid."'")->find();
            //log
            $this->fenxiao_log($userinfo,$one,$one_money,$money,'一级CEO佣金',1,$order_id);
            //模板消息
            $content = "一级CEO佣金：订单".$order['order_id'].$order['order_title'].",".$order['realname']."(".$order['uid'].")";
            $this->_shouruMsg($one, $order, $one_money, $content);
        }
        
        
        //第二级
        $refer_uid = $one['refer_uid'];
        $two = $this->memberModel->where("uid = '".$refer_uid."'")->find();
        if($two){
            //只分ceo
            if($two['grade_id'] >= 3){
                return;
            }
            $two_money = $money*$two_bili;
            $this->memberModel->where("uid = '".$refer_uid."'")->setInc('money',$two_money);
            $two = $this->memberModel->where("uid = '".$refer_uid."'")->find();
            //log
            $this->fenxiao_log($userinfo,$two,$two_money,$money,'二级CEO佣金',2,$order_id);
            //模板消息
            $content = "二级CEO佣金：订单".$order['order_id'].$order['order_title'].",".$order['realname']."(".$order['uid'].")";
            $this->_shouruMsg($two, $order, $two_money, $content);
        }
        
    }
    
    /*
     * 分销佣金log
     * $orderuser 下单人信息
     * $user 分钱用户信息
     * $money 佣金数额
     * $order_money  订单金额
     * $content 
     */
    public function fenxiao_log($orderuser,$user,$money,$order_money,$content,$from_jibie,$order_id){
        $log = array(
            'uid' => $user['uid'],
            'nickname' => $user['realname']?$user['realname']:$user['nickname'],
            'mtype' => 1,
            'content' => $content,
            'logtype' => 1,
            'money' => $money,
            'order_paymoney' => $order_money,
            'from_jibie' => $from_jibie,
            'un_lock' => 1,
            'order_id' => $order_id,
            'order_uid' => $orderuser['uid'],
            'order_nickname' => $orderuser['realname']?$orderuser['realname']:$orderuser['nickname'],
            'pay_time' => date("Y-m-d H:i:s"),
            'create_time' =>date("Y-m-d H:i:s"),
            'manager_username' => $this->admininfo['username'],
            'cash_money' => $user['money']            
        );
        $this->moneylogModel->add($log);
    }
    

    /*
     * 查订单所属皇冠
     */
    public function getKing($refer_uid) {
        $this->king = $user = $this->memberModel->where("uid = '".$refer_uid."'")->find();
        if($user['grade_id'] == 2){
            $this->getKing($user['refer_uid']);
        }
        return $this->king;
    }


 
    
    /*
     * 升级通知,模板消息
     *
     */
    protected function _shengjiMsg($userinfo,$old,$new){
    
        //发送升级模板消息
        //判断是否关注, 没关注就别发了
        if(!$userinfo['subscribe']){
            //return false;
            //TODO
        }
    
        //发送模板消息
        $msg = $this->_sendsjmsgtmp($userinfo,$old,$new);//拼接模板消息
    
        $msgttt = array(
            "uid" => $userinfo['uid'],
            "openid" => $userinfo['openid'],
            "nickname" => $userinfo['nickname'],
            "groupid" => -1,
            "content" => $msg,
            "send_priority" => 1,
            "create_time" => time(),
            "send_time" => time(),
            "status" => -1,
            "send_plan_time" => time()
        );
        $tmpmsgModel = new tmpmsgModel();
        $tmpmsgModel->addtmpmsg($msgttt);//添加消息到数据库队列
    
        return true;
    }
    
    
    /*
     * 升级消息
     *
     */
    protected function _sendsjmsgtmp($userinfo,$old,$new){
    
        $grade_arr = $this->grade_arr;
    
        $tmp_id = $this->tmpl['DENG_JI']['tmp_id'];
        $color = $this->tmpl['DENG_JI']['color'];
    
        $url = get_domain()."/mobile/user/grade/";
        $footer ='\\n'."点击查看详情...";
        $msg = array(
            "touser" => $userinfo['openid'],
            "template_id" => $tmp_id,//
            'url' => $url,
            "topcolor" => $color,
            'data' => array(
                'first' => array(
                    'value' => urlencode("恭喜,你的等级已提升~".'\\n'),
                    'color' => $color
                ),
                'keyword1' => array(
                    'value' => urlencode($grade_arr[$old]),//原先等级
                    'color' => $color,
                ),
                'keyword2' => array(
                    'value' => urlencode($grade_arr[$new]),//new等级
                    'color' => $color,
                ),
                'remark' => array(
                    'value' => urlencode($footer),
                    'color' => $color,
                ),
            ),
        );
    
        return $msg = urldecode(json_encode($msg));
    }
    
    

    /*
     * 收入模板消息
     * 拼接收入模板
     */
    protected function _shouruTmp($userinfo,$order,$money,$content,$type=0){
    
        $tmp_id = $this->tmpl['FEN_XIAO']['tmp_id'];
        $color = $this->tmpl['FEN_XIAO']['color'];
    
        $url = get_domain()."/mobile/moneylists/money/";
        $footer ="资金已转入你的账户".'\\n\\n'."点击查看详情...";
        $msg = array(
            "touser" => $userinfo['openid'],
            "template_id" => $tmp_id,
            'url' => $url,
            "topcolor" => $color,
            'data' => array(
                'first' => array(
                    'value' => urlencode($content.'\\n'),
                    'color' => $color
                ),
                'keyword1' => array(
                    'value' => urlencode($order['order_sn']),//订单号
                    'color' => $color,
                ),
                'keyword2' => array(
                    'value' => urlencode($order['order_cashmoney']),//订单金额
                    'color' => $color,
                ),
                'keyword3' => array(
                    'value' => urlencode($money),//订单金额
                    'color' => $color,
                ),
                'keyword4' => array(
                    'value' => urlencode($order['pay_time']),
                    'color' => $color,
                ),
                'remark' => array(
                    'value' => urlencode($footer),
                    'color' => $color,
                ),
            ),
        );
    
        return $msg = urldecode(json_encode($msg));
    }
    
    
    /*
     * 收入提醒
     */
    protected function _shouruMsg($userinfo,$order,$money,$content){
        //判断是否关注, 没关注就别发了
        if(!$userinfo['subscribe']){
            //TODO
            //  return false;
        }
         
        //发送模板消息
        $msg = $this->_shouruTmp($userinfo,$order,$money,$content);//拼接模板消息
    
        $msgttt = array(
            "uid" => $userinfo['uid'],
            "openid" => $userinfo['openid'],
            "nickname" => $userinfo['nickname'],
            "groupid" => -1,
            "content" => $msg,
            "send_priority" => 1,
            "create_time" => time(),
            "send_time" => time(),
            "status" => -1,
            "send_plan_time" => time()
        );
        $tmpmsgModel = new tmpmsgModel();
        $tmpmsgModel->addtmpmsg($msgttt);//添加消息到数据库队列
    
        return true;
    }
    
    /*
     * 凝胶进货量统计
     */
    public function ningjiao(){
        $goods_id = get('goods_id');
        $today=date("Y-m-d");
        if(get('year')&&get('month')){
            $firstday = date(get('year').'-'.get('month').'-01 00:00:00', strtotime($today));
            $lastday = date(get('year').'-'.get('month').'-d 00:00:00', strtotime("$firstday +1 month -1 day"));
            $y = get('year');
            $m = get('month');
        }else{
            $firstday = date('Y-m-01 00:00:00', strtotime($today));
            $lastday = date('Y-m-d 00:00:00', strtotime("$firstday +1 month -1 day"));
            $y = date('Y');
            $m = date('m');
        }
        
        $memberlist = $this->_getJiangli(16, $firstday, $lastday);
       
        $this->assign('year',$y);
        $this->assign('month',$m);
        $this->assign('list',$memberlist);
        $this->display();
    }
    
    protected function _getJiangli($goods_id,$firstday,$lastday){
        $memberlist = $this->memberModel->where(array('grade_id'=>array('gt',3)))->field('uid,realname,nickname')->select();
        foreach($memberlist as $k=>$v){
            $order_where = array(
                'pay_time' => array('between',array($firstday,$lastday)),
                'checked' => array('in',array(1,2,5)),
                'uid' => $v['uid'],
                'goods_ids' => array('like','%'.$goods_id.'%')
            );
            //$inorder = "FIND_IN_SET('16',goods_ids)";
            $orders = $this->orderModel->where($order_where)->field('goods_sale')->select();
            //dump($v['uid']);
            $count = 0;
            foreach ($orders as $kk=>$vv){
               /*  $saleArr = explode(',',$vv['goods_sale']);
                $count += $saleArr[1]; */
                
                $goods_sale = $vv['goods_sale'];
                $sale_arr = explode(";",$goods_sale);
                foreach($sale_arr as $sale){
                    $sale = explode(",",$sale);
                    if($goods_id == $sale[0]){
                        $count += $sale[1];
                    }
                }
            }
            $memberlist[$k]['ningjiao'] = $count;
            
            if($goods_id == 16){
                $money = array(
                    0,5,10,15
                );
                if($count==0){
                    unset($memberlist[$k]);
                }elseif($count>=300 && $count<600){
                    $memberlist[$k]['money'] = $count*$money[1];
                }elseif($count>=600 && $count<1000){
                    $memberlist[$k]['money'] = $count*$money[2];
                }elseif($count>=1000){
                    $memberlist[$k]['money'] = $count*$money[3];
                }
            }elseif($goods_id == 2 || $goods_id == 5){
                $money = array(
                    0,3,5,10
                );
                if($count==0){
                    unset($memberlist[$k]);
                }elseif($count>=500 && $count<1000){
                    $memberlist[$k]['money'] = $count*$money[1];
                }elseif($count>=1000 && $count<2000){
                    $memberlist[$k]['money'] = $count*$money[2];
                }elseif($count>=2000){
                    $memberlist[$k]['money'] = $count*$money[3];
                }
            }
        }
        
        return $memberlist;
    }
  
    
    public function baodan(){
        if(IS_AJAX){
            $allow = array(
                'realname','refer_uid','number',"mobile",'order_type','address','goods_id',
                'money','grade_id','idcard','bzj_money','pxf_money'
            );
            $data = param_filter($_POST, $allow);
            if(!$data['order_type']){
                return_json(1,'请选择订单类型');
            }
            if(!$data['mobile']){
                return_json(1,'请输入手机号');
            }
            if(!check_mobile($data['mobile'])){
                return_json(1,'手机号码格式错误');
            }
            if($data['order_type'] == 1 && !$data['refer_uid']){
                return_json(1,'请输入推荐人uid');
            }
            if($data['number']<0){
                return_json(1,'报单数量必须大于等于0');
            }
            
            if($data['order_type'] == 2){
                $member = $this->memberModel->where(array('mobile'=>$data['mobile']))->find();
                if(!$member){
                    return_json(1,'报单人不存在,请检查手机号');
                }
                $data['uid'] = $member['uid'];
            }elseif($data['order_type'] == 1){
                if($data['number']<0){
                    return_json(1,'报单数量必须大于等于0');
                }
                
                if($data['grade_id']<2){
                    return_json(1,'请选择报单等级');
                }
            
                $member = $this->memberModel->where(array('mobile'=>$data['mobile']))->find();
                if($member){
                    return_json(1,'报单用户已存在,请检查手机号');
                }
                $refer = $this->memberModel->getMember(array('uid'=>$data['refer_uid']));
                if(!$refer){
                    return_json(1,"推荐人不存在,请重新填写");
                }
                $data['refer_nickname'] = $refer['realname'] ? $refer['realname'] : $refer['nickname'];
                
                $grade = $data['grade_id'];
                $data['grade_id'] = $grade;//省代
                
                //检查身份证
                $idcard = $data['idcard'];
                $len = strlen($idcard);
                if($len != 18){
                    return_json(1,"身份证号码填写错误,请重新填写");
                }
                $idcardold = $this->memberModel->where(array('idcard'=>$idcard))->find();
                if($idcardold) {
                    return_json(1,'身份证号码已存在');
                }
                
                $pass = substr($idcard, -6);
                
                $data['password'] = md5($pass.C('SALT'));
                
                $data['regfrom'] = "baodan";
                $data['create_time'] = date("Y-m-d H:i:s");
                $res = $this->memberModel->add($data);
                if($res){
                    $data['uid'] = $res;
                }else{
                    return_json(1,'报单失败,请重试');
                }
            }
            //生成订单
            $orderid = $this->_addNingjiaoOrder($data);
            if($orderid){
                $option['baodan'] = true;
                $order = $this->orderModel->where(array('order_id'=>$orderid))->find();
                $memberinfo = $this->memberModel->where(array('uid'=>$data['uid']))->find();
                //分佣金
                $callback = new OrdercallbackController($option);
                $callback->adminBaodan($order, $memberinfo, $data);
                return_json(0,"操作成功",'','/admin/finance/baodan');
            }
        }
        
        
        $gradearr = M('grade')->where('grade_id>1')->getField('grade_id,grade_name',true);
        $this->assign('gradearr',$gradearr);
        
        $goodsList = M('goods')->select();
        $this->assign('goodsList',$goodsList);
        $this->display();
        
        
    }
    
    protected function _addNingjiaoOrder($data){
        $user = $this->memberModel->getMember(array('uid'=>$data['uid']));
        $goods = M('goods')->where(array('goods_id'=>1))->find();
        $goods['num'] = $data['number'];
        $goods['shop_price'] = $goods['grade2_price'];
        $goodsinfo[] = $goods;
        $money = $goods['grade'.$data['grade_id'].'_price']*$data['number'];
//        $money = $data['money'];

        $delivery = array(
            'delivery_mobile' => $user['mobile'],
            'address' => $data['address']
        );
        $order = array(
            'uid' => $user['uid'],
            'realname' => $user['realname'],
            'nickname' => $user['realname'],
            'refer_uid' => $user['refer_uid'],
            'refer_nickname' => $user['refer_nickname'],
            'checked' => 2,//报单数量为1时直接订单为已完成
            'pay_time' => date('Y-m-d H:i:s'),
            'create_time' => date('Y-m-d H:i:s'),
            'order_title' => "后台报单",
            'delivery_mobile' => $user['mobile'],
            'delivery_name' => $user['realname'],
            'order_cashmoney' => $money,
            'pay_orgmoney' => $money,
            'all_money' => $money,
            'goods' => serialize($goodsinfo),
            'order_type' => $data['order_type'],
            'delivery' => serialize($delivery),
            'order_from' => 2,
            'manager_username' => $this->admininfo['username'],
            'sj_gnums' => $data['number'],
            'bzj_money' => $data['bzj_money'],
            'pxf_money' => $data['pxf_money']
        );
        $o = M('order');
        $orderid = $o->add($order);
        if($orderid){
            return $orderid;
        }
        return false;
        
    }
    

    /*
     * 面膜进货量统计
     */
    public function mianmo(){
        $today=date("Y-m-d");
        if(get('year')&&get('month')){
            $firstday = date(get('year').'-'.get('month').'-01 00:00:00', strtotime($today));
            $lastday = date(get('year').'-'.get('month').'-d 00:00:00', strtotime("$firstday +1 month -1 day"));
            $y = get('year');
            $m = get('month');
        }else{
            $firstday = date('Y-m-01 00:00:00', strtotime($today));
            $lastday = date('Y-m-d 00:00:00', strtotime("$firstday +1 month -1 day"));
            $y = date('Y');
            $m = date('m');
        }
    
        $memberlist = $this->_getJiangli(2, $firstday, $lastday);
         
        $this->assign('year',$y);
        $this->assign('month',$m);
        $this->assign('list',$memberlist);
        $this->display();
    }
    /*
     * 面膜进货量统计
     */
    public function wsj(){
        $today=date("Y-m-d");
        if(get('year')&&get('month')){
            $firstday = date(get('year').'-'.get('month').'-01 00:00:00', strtotime($today));
            $lastday = date(get('year').'-'.get('month').'-d 00:00:00', strtotime("$firstday +1 month -1 day"));
            $y = get('year');
            $m = get('month');
        }else{
            $firstday = date('Y-m-01 00:00:00', strtotime($today));
            $lastday = date('Y-m-d 00:00:00', strtotime("$firstday +1 month -1 day"));
            $y = date('Y');
            $m = date('m');
        }
    
        $memberlist = $this->_getJiangli(5, $firstday, $lastday);
         
        $this->assign('year',$y);
        $this->assign('month',$m);
        $this->assign('list',$memberlist);
        $this->display();
    }
    
    
    /*
     * 计算产品当日出货量
     */
    public function api(){
        $id = get('id');
        $num = $this->countChuhuo($id);
        echo $num;
    }
    
    public function countChuhuo($id){
        $start = date('Y-m-d 00:00:00', strtotime("-1 day"));
        $end = date('Y-m-d 00:00:00');
        /* dump($start);dump($end); */
        $where = "(checked = 1 OR checked = 2 OR checked = 5)";
        $where .= " AND create_time>='".$start."'";
        $where .= " AND create_time<='".$end."'";
        $where .= " AND create_time>='".$start."'";
        $where .= " AND goods_ids like '%".$id."%'";
        $sale_num = 0;
        $orders = $this->orderModel->where($where)->select();
        foreach ($orders as $k=>$v){
            $goods_sale = $v['goods_sale'];
            $sale_arr = explode(";",$goods_sale);
            foreach($sale_arr as $sale){
                $sale = explode(",",$sale);
                if($id == $sale[0]){
                    $sale_num += $sale[1];
                }
            }
        }
        return $sale_num;
    }
   
    public function setnote() {
        $allow = array(
            'atm_id','note'
        );
        $data = param_filter($_POST, $allow);
        if(!$data['note']){
            return_json(1,'请输入备注内容');
        }
        $res = $this->withdrawModel->where(array('atm_id'=>$data['atm_id']))->save($data);
        if($res){
            return_json(0,'保存成功');
        }else{
            return_json(1,'无修改');
        }
    }
    
    public function baodanlog(){
        $where = array(
            'order_from' => 2
        );
        if(get('order_id')){
            $where['order_id'] = get('order_id');
        }
        if(get('user_id')) {
            $where['uid'] = get('user_id');
        }
        
        $list = $this->orderModel->where($where)->order('order_id DESC')->select();
        $this->assign('datalist',$list);
        $this->display();
    }
}
